﻿Imports System.Text
Public Class UpdateFormTreeBase

#Region "自定义属性"
    Dim _TextBrowser As String = ""
    Public Property TextBrowser() As String
        Get
            Return _TextBrowser
        End Get
        Set(ByVal value As String)
            _TextBrowser = value
        End Set
    End Property

    Private _typeId As Integer = 0
    Public Property TypeId() As Integer
        Get
            Return _typeId
        End Get
        Set(ByVal value As Integer)
            _typeId = value
        End Set
    End Property
#End Region

#Region "窗体初始化事件"
    Private Sub TreeTableFromBase_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If DesignMode Then
            Exit Sub
        End If
        InitUpdate()
        RefreshData()
    End Sub

    Public Overridable Sub InitUpdate()
        ID = "ID"
        ParentID = "ParentID"
        DisplayName = "Name"
        TableName = "XscBugType"
        Me.txtParentName1.Tag = ""
    End Sub

    Private Sub LoadData(Optional ByVal tdParent As TreeNode = Nothing, Optional ByVal idParent As String = "")

        Dim rs As ADODB.Recordset = ct.GetTable(MakeSql(idParent))

        If rs Is Nothing Then Exit Sub

        If rs.EOF Then
            GoTo end1
        End If

        While Not rs.EOF
            Dim td As TreeNode = Nothing
            Dim strTemp As String = ""

            If Not String.IsNullOrEmpty(rs.Fields(DisplayName).Value.ToString()) Then
                strTemp = rs.Fields(DisplayName).Value.ToString()
            End If

            If tdParent IsNot Nothing Then
                td = tdParent.Nodes.Add(strTemp)
            Else
                td = Me.MyTreeView1.Nodes.Add(strTemp)
            End If

            strTemp = ""

            If Not String.IsNullOrEmpty(rs.Fields(ID).Value.ToString()) Then
                strTemp = rs.Fields(ID).Value.ToString()
            End If

            td.Tag = strTemp

            strTemp = ""

            If Not String.IsNullOrEmpty(rs.Fields(ID).Value.ToString()) Then
                strTemp = rs.Fields(ID).Value.ToString()
            End If

            If Not String.IsNullOrEmpty(strTemp) Then
                LoadData(td, strTemp)
            End If

            rs.MoveNext()
        End While
end1:
        rs.Close()
        System.Runtime.InteropServices.Marshal.ReleaseComObject(rs) '20100531
        rs = Nothing
    End Sub
#End Region

#Region "插入按钮事件事件"
    Private Sub btnIns_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIns.Click
        DoInsert()
    End Sub

    Public Overridable Function DoInsert() As Boolean
        Dim frm As New XscTypeAdd
        frm.strName = Me.strName
        frm.iType = Me.iType
        frm.TypeId = Me.TypeId
        frm.ShowDialog()
        If frm.bAdd Then
            RefreshData()
        End If
        DoInsert = False
    End Function

#End Region

#Region "更新按钮事件"

    Public Overridable Sub 更新事件(ByVal ND As TreeNode)

    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        If Me.MyTreeView1.SelectedNode IsNot Nothing Then
            Dim ND As TreeNode = Me.MyTreeView1.SelectedNode
            Dim strId As String = Me.MyTreeView1.SelectedNode.Tag.ToString

            Dim sb As New StringBuilder
            sb.Append(" select A.ID,A.Name,A.ParentID,B.NAME AS ParentName ")
            sb.Append(" from XscBugType A ")
            sb.Append(" left join XscBugType B ")
            sb.Append(" On        A.ParentID=B.ID ")
            sb.Append(" Where A.ID='" + strId + "'")
            Dim rs As ADODB.Recordset = ct.GetTable(sb.ToString())
            If rs IsNot Nothing Then
                rs.Close()
                System.Runtime.InteropServices.Marshal.ReleaseComObject(rs) '20100531
                rs = Nothing
                更新事件(ND)
                选择(Me.MyTreeView1.TopNode, strId)
            End If
        End If
    End Sub

    '更新关联表
    Public Overridable Function DoUpdateLink() As Boolean
        DoUpdateLink = True
    End Function
#End Region

#Region "删除按钮事件"
    Public strID As String = ""
    Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDel.Click
        '删除前判断数据是否存在
        If DoDeleteCheck() = False Then Exit Sub
        '此数据有子数据时提示是否删除
        If DoDeleteCheckChild() = False Then Exit Sub
        '删除其他关联表
        If DoLinkTable() = False Then Exit Sub
        '删除自己
        If DoDelete() = False Then Exit Sub
    End Sub

    '做删除CHECK
    Public Overridable Function DoDeleteCheck() As Boolean
        If UTIL.CUtil.ConvertText(Me.strID) = "" Then
            ShowMessageBox("请选择要更新的记录")
            Return False
        End If
        Dim sb As New StringBuilder

        sb.Append("select * from XscBugType where id='" + UTIL.CUtil.ConvertText(Me.strID) + "'")
        If Not (ct.GetExistSql(sb.ToString())) Then
            ShowMessageBox("此条记录不存在")
            RefreshData()
            Return False
        End If

        DoDeleteCheck = True
    End Function

    '此数据有子数据时提示是否删除
    Public Overridable Function DoDeleteCheckChild() As Boolean

        Dim sb As New StringBuilder
        sb.Append("select * from XscBugType where ParentID='" + UTIL.CUtil.ConvertText(Me.strID) + "'")
        If (ct.GetExistSql(sb.ToString())) Then
            If ShowMessageResult("有管理此数据的子数据，是否删除") = Windows.Forms.DialogResult.Yes Then
                Return True
            Else
                Return False
            End If
        End If

        Return True
    End Function

    '真正删除
    Public Overridable Function DoDelete() As Boolean

        If (ShowMessageResult("是否要删除此条数据") = Windows.Forms.DialogResult.No) Then
            Return False
        End If

        Dim ids() As String = GetChildIdAndSelf(Me.strID)

        Dim sb As New StringBuilder

        sb.Append("delete from XscBugType where id=?")

        Dim cmd As New ADODB.Command
        cmd.CommandText = sb.ToString
        Dim pa As ADODB.Parameter = cmd.CreateParameter("ID", ADODB.DataTypeEnum.adVarNumeric, ADODB.ParameterDirectionEnum.adParamInput)
        pa.NumericScale = 10
        pa.Precision = 0
        cmd.Parameters.Append(pa)

        For Each strId As String In ids
            cmd.Parameters(0).Value = strId
            ct.ExcCommand(cmd)
            '添加删除记录功能  A-2010-03-24
            ct.AddDeleteDetal("XscBugType", New String() {"ID", "", ""}, New String() {strId, "", "", ""}, Me.strName)
            '添加删除记录功能  A-2010-03-24 
        Next

        If Me.strID = "" Then
            cmd.Parameters(0).Value = DBNull.Value
        Else
            cmd.Parameters(0).Value = Me.strID
        End If

        If (ct.ExcCommand(cmd)) Then
            '添加删除记录功能  A-2010-03-24
            ct.AddDeleteDetal("XscBugType", New String() {"ID", "", ""}, New String() {Me.strID, "", "", ""}, Me.strName)
            '添加删除记录功能  A-2010-03-24 
            ShowMessageBox("删除成功")
            选择(Me.MyTreeView1.SelectedNode, Me.strID)
            RefreshData()
            Return True
        Else
            ShowMessageBox("删除失败")
            RefreshData()
            Return False
        End If

    End Function

    ''删除其他关联表
    Public Overridable Function DoLinkTable() As Boolean
        DoLinkTable = True
    End Function
#End Region

#Region "关闭按钮事件"
    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        DoClose()
    End Sub
    Public Overridable Function DoClose() As Boolean
        Me.Close()
        Return True
    End Function
#End Region

#Region "选择按钮事件"
    Private Sub btnSelectType2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectType2.Click
        SelectChange()
    End Sub

    Public Overridable Sub SelectChange()
        Dim ttf As Wys.Control.Vb.TreeTableFromBase = New Wys.Control.Vb.TreeTableFromBase(Me.txtParentName1.Tag.ToString())
        ttf.ID = "ID"
        ttf.ParentID = "ParentID"
        ttf.DisplayName = "Name"
        ttf.TableName = "XscBugType"
        ttf.TypeId = TypeId
        ttf.Text = TextBrowser
        ttf.ShowDialog()
        If (Not ttf.Cancel) Then
            txtParentName1.Text = ttf.DisplayNameValue
            txtParentName1.Tag = ttf.Result
        End If
        txtParentName1.Text = ct.GetParentName(txtParentName1.Tag.ToString(), "XscBugType", "Name", "ParentID", "ID")
        RefreshData()
    End Sub


#End Region

#Region "父表"

#Region "父主键"
    Dim _ParentId As String = ""
    Public Property ParentID() As String
        Get
            Return _ParentId
        End Get
        Set(ByVal value As String)
            _ParentId = value
        End Set
    End Property
#End Region

#Region "树要显示的名称"
    Dim _DisplayName As String = ""
    Public Property DisplayName() As String
        Get
            Return _DisplayName
        End Get
        Set(ByVal value As String)
            _DisplayName = value
        End Set
    End Property
#End Region

#Region "父表名"
    Dim _tableName As String = ""
    Public Property TableName() As String
        Get
            Return _tableName
        End Get
        Set(ByVal value As String)
            _tableName = value
        End Set
    End Property

#Region "主键"
    Dim _Id As String = ""
    Public Property ID() As String
        Get
            Return _Id
        End Get
        Set(ByVal value As String)
            _Id = value
        End Set
    End Property
#End Region

#End Region

#Region "生成的SQL"
    Private Function MakeSql(Optional ByVal strId As String = "") As String
        MakeSql = ""
        Dim SB As New StringBuilder
        SB.Append(" Select ")
        If Not String.IsNullOrEmpty(ID) Then
            SB.Append(" " + ID + " ")
        End If

        If Not String.IsNullOrEmpty(ParentID) Then
            SB.Append("," + ParentID + " ")
        End If

        If Not String.IsNullOrEmpty(DisplayName) Then
            SB.Append("," + DisplayName + " ")
        End If

        SB.Append(" From " + TableName + " ")

        SB.Append(" Where  " + ParentID)

        If Not String.IsNullOrEmpty(strId) Then
            SB.Append("=" + """")
            SB.Append(strId)
            SB.Append("""")
        Else
            SB.Append(" is null ")
        End If

        '2009-12-25
        If _typeId <> -1 Then
            SB.Append(" And Type='" + Me.TypeId.ToString() + "' ")
        End If
        '2009-12-25

        Return SB.ToString
    End Function
#End Region

#End Region

#Region "树的选择的节点的改变事件"
    Protected Overridable Sub SelectData(ByVal strId As String)
        Me.strID = strId
    End Sub

    Private Sub MyTreeView1_NodeMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles MyTreeView1.NodeMouseClick
        SelectData(e.Node.Tag)
    End Sub

#End Region

#Region "刷新事件"
    Protected Overridable Sub RefreshData()
        Form_Clear()
        Me.MyTreeView1.Nodes.Clear()
        Dim nd As TreeNode = Me.MyTreeView1.Nodes.Add("根/" + Me.txtParentName1.Text.TrimEnd())
        nd.Tag = "根" + Me.txtParentName1.Text.TrimEnd()
        LoadData(nd, Me.txtParentName1.Tag)
        nd.Expand()
        'Me.MyTreeView1.ExpandAll()
    End Sub
#End Region

#Region "清除窗体"
    Protected Overridable Sub Form_Clear()
        Me.strID = ""
    End Sub
#End Region

#Region "所以得子ID"
    Private Function GetChildIdAndSelf(ByVal strParentId As String) As String()
        Dim result As New List(Of String)
        Dim rs As New ADODB.Recordset
        If (Not String.IsNullOrEmpty(strParentId)) Then
            rs = ct.GetTable("select Name,ID from XscBugType where ParentID='" + strParentId + "'")
        Else
            rs = ct.GetTable("select Name,ID from XscBugType where ParentID is null")
        End If
        If (rs Is Nothing) Then
            Return Nothing
        End If

        If rs.EOF Then
            GoTo end1
        End If
        Dim str As String = ""
        Dim strid1 As String = ""
        While (Not rs.EOF)
            str = rs.Fields("ID").Value.ToString()
            strid1 = str
            If (Not result.Contains(str)) Then
                result.Add(str)
            End If
            Dim resultChild() As String = GetChildIdAndSelf(strid1)
            If resultChild Is Nothing Then
                GoTo end2
            End If
            For Each strItem As String In resultChild
                If Not result.Contains(strItem) Then
                    result.Add(strItem)
                End If
            Next
end2:
            rs.MoveNext()
        End While
end1:
        rs.Close()
        System.Runtime.InteropServices.Marshal.ReleaseComObject(rs) '20100531
        rs = Nothing
        Return result.ToArray()
    End Function
#End Region

    Private Sub MyTreeView1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyTreeView1.MouseDoubleClick
        If Me.MyTreeView1.SelectedNode IsNot Nothing Then
            Dim ND As TreeNode = Me.MyTreeView1.SelectedNode
            Dim strId As String = Me.MyTreeView1.SelectedNode.Tag.ToString
            Me.strID = strId
            Dim sb As New StringBuilder
            sb.Append(" select A.ID,A.Name,A.ParentID,B.NAME AS ParentName ")
            sb.Append(" from XscBugType A ")
            sb.Append(" left join XscBugType B ")
            sb.Append(" On        A.ParentID=B.ID ")
            sb.Append(" Where A.ID='" + strId + "'")
            Dim rs As ADODB.Recordset = ct.GetTable(sb.ToString())
            If rs IsNot Nothing Then
                rs.Close()
                System.Runtime.InteropServices.Marshal.ReleaseComObject(rs) '20100531
                rs = Nothing
                更新事件(ND)
                选择(Me.MyTreeView1.TopNode, strId)
                'Me.MyTreeView1
            End If
        End If
    End Sub

    Public Function 选择(ByVal nd As TreeNode, ByVal id As String) As Boolean

        If nd Is Nothing Then
            Return False
        End If

        If nd.Tag.ToString = id Then
            MyTreeView1.Focus()
            Me.MyTreeView1.SelectedNode = nd
            Return True
        End If

        For Each nd2 As TreeNode In nd.Nodes
            If 选择(nd2, id) Then
                选择 = True
                Exit Function
            End If
        Next

        Return False
    End Function
End Class